import { ref, Ref, toValue, watchEffect } from "vue";
export function useRecord(data: Ref<MediaStream | null> | MediaStream) {
    const stream = ref<MediaStream | null>(null)
    watchEffect(() => {
        // console.log("视频流变化", data.value)
        stream.value = toValue(data)
    })
    const recordedBlobs = ref<Blob[]>([])
    let mediaRecorder = ref<MediaRecorder | null>(null)

    function record() {
        const options = {}
        try {
            if (stream.value) {
                mediaRecorder.value = new MediaRecorder(stream.value, options)
            } else {
                console.log("无法获取到视频流", stream.value)
            }
        } catch (error) {
            console.log("record error", error)
        }
        if (mediaRecorder.value) {
            mediaRecorder.value.onstop = (event) => {
                console.log('Recorder stopped: ', event);
                console.log('Recorded Blobs: ', recordedBlobs.value);
            };
            mediaRecorder.value.ondataavailable = (e) => {
                if (e.data && e.data.size > 0) {
                    recordedBlobs.value.push(e.data)
                }
            };
            mediaRecorder.value.start();
        }

    }
    function recordStop() {
        if (mediaRecorder.value) {
            mediaRecorder.value.stop()
            mediaRecorder.value = null
        }
    }
    function download() {
        const blob = new Blob(recordedBlobs.value, { type: 'video/mp4' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = 'test.mp4';
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }, 100);
    }
    return {
        record,
        recordStop,
        recordedBlobs,
        mediaRecorder,
        download
    }
}